<?php

namespace App\Api\Controllers;


use App\Models\Banner;
use App\Models\Goods;
use App\Models\WebConfig;
use Illuminate\Support\Facades\DB;
use Dingo\Api\Routing\Helpers;
use Illuminate\Routing\Controller;

class HomeController extends Controller
{
    use Helpers;

    /**
     * 名称：首页banner图片
     * 必要条件：
     * 功能：
     * 任务：
     */
    public function banner()
    {
        $data=Banner::where('status',1)->orderBy('sort')->get();
        $host=request()->getSchemeAndHttpHost();
        foreach ($data as $v){
            $v->img=$host.'/uploads/'.$v->img;
            $v->url=$host.$v->url;
        }
        return $this->response->array([
            'status_code'=>200,
            'message'=>'获取数据成功',
            'result'=>$data
        ]);
    }
    //首页推荐,默认推荐同校的用户
    public function recommend()
    {
        $user=$this->auth->user();//当前用户
        $goodsList=[];
        if($user->university_id && $user->campus_id){
            //当前用户录入了学校信息则推荐本校的书籍
            //首页获取4本，同校，数量可售数量最多的书
            $goodsList=DB::table('depot')
                ->where([['university_id',$this->user->university_id],['campus_id',$this->user->campus_id],['can_sale_num','>',0]])
                ->select('goods_id as goods_id',DB::raw("sum(can_sale_num) as can_sale_num"))
                ->groupBy('goods_id')
                ->orderBy('can_sale_num','desc')
                ->limit(4)
                ->get();
            foreach ($goodsList as $v){
                $tmp=Goods::find($v->goods_id);
                $v->title=$tmp->title;
                $v->img=$tmp->img;
                $v->publisher=$tmp->publisher;
                $v->author=$tmp->author;
            }
        }
        if(count($goodsList)<4){
            //如果取出的书籍数量小于4则重新取平台库中的数据
            $goodsList=Goods::orderByRaw("rand()")
                ->select('id as goods_id','title','author','img','publisher')
                ->limit(4)
                ->get();
        }
        return $this->response->array([
            'status_code'=>200,
            'message'=>'获取数据成功',
            'result'=>$goodsList
        ]);
    }

    //更多推荐
    public function recommendMore()
    {
        $data=Goods::paginate(8);
        $extra_discount=WebConfig::where('name','extra_discount')->value('value')?:0;
        $goodsCtrl=new GoodsController();
        foreach ($data as $v){
            $v->discount +=$extra_discount;
            $v->sale_status=$goodsCtrl->checkGoodsStatus($v->id);
        }
        return $this->response->array([
            'status_code'=>200,
            'message'=>'获取数据成功',
            'result'=>$data
        ]);
    }
}
